package ljye.com.ljye.adapter;

import android.app.Activity;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.util.List;

import ljye.com.ljye.R;
import ljye.com.ljye.utils.CommonViewHolder;

/**
 * Created by Administrator on 2017/1/6.
 */

public class Introduce_IMG_adapter extends BaseAdapter {
    private List<String> imglist;
    private Activity activity;

    public Introduce_IMG_adapter(Activity activity, List<String> imglist) {
        this.imglist = imglist;
        this.activity = activity;
    }

    @Override
    public int getCount() {
        return imglist == null ? 0 : imglist.size();
    }

    @Override
    public Object getItem(int i) {
        return imglist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        CommonViewHolder holder = CommonViewHolder.createCVH(view, viewGroup, R.layout.item_institution_introduce);
        final ImageView imageView = holder.getIv(R.id.img);//图片
        Transformation transformation = new Transformation() {

            @Override
            public Bitmap transform(Bitmap source) {

                int targetWidth = imageView.getWidth();
//                    LogCat.i("source.getHeight()="+source.getHeight()+",source.getWidth()="+source.getWidth()+",targetWidth="+targetWidth);

                if (source.getWidth() == 0) {
                    return source;
                }

                //如果图片小于设置的宽度，则返回原图
                if (source.getWidth() < targetWidth) {
                    return source;
                } else {
                    //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
                    double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                    int targetHeight = (int) (targetWidth * aspectRatio);
                    if (targetHeight != 0 && targetWidth != 0) {
                        Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                        if (result != source) {
                            source.recycle();
                        }
                        return result;
                    } else {
                        return source;
                    }
                }

            }

            @Override
            public String key() {
                return "transformation" + " desiredWidth";
            }

        };


        Picasso.with(activity)
                .load(imglist.get(i))
                .placeholder(R.drawable.ic_default_image)
                .transform(transformation)
                .into(imageView);
        return holder.convertView;
    }
}
